package com.joy.ogljoy_01.opengl;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import com.joy.ogljoy_01.opengl.util.ClassUtil;

public class RenderBuffer {

	/** 默认的索引系列 */
	private final static short[] indices = new short[] { 0, 1, 2, 1, 2, 3 };

	private ByteBuffer vertexBytes;
	private FloatBuffer vertexs;

	private ByteBuffer texcoordBytes;
	private FloatBuffer texcoords;

	private ByteBuffer indexBytes;
	private ShortBuffer indexs;
	private short index;

	public RenderBuffer(int count) {
		vertexBytes = ByteBuffer.allocateDirect(count * 4 * 2 * 4);
		vertexBytes.order(ByteOrder.nativeOrder());
		vertexs = vertexBytes.asFloatBuffer();
		
		texcoordBytes = ByteBuffer.allocateDirect(count * 4 * 2 * 4);
		texcoordBytes.order(ByteOrder.nativeOrder());
		texcoords = texcoordBytes.asFloatBuffer();

		indexBytes = ByteBuffer.allocateDirect(count * 6 * 2);
		indexBytes.order(ByteOrder.nativeOrder());
		indexs = indexBytes.asShortBuffer();
	}

	public FloatBuffer getVertexs() {
		return vertexs;
	}

	public FloatBuffer getTexcoords() {
		return texcoords;
	}

	public ShortBuffer getIndexs() {
		return indexs;
	}

	public void clear() {
		vertexs.clear();
		texcoords.clear();
		indexs.clear();
		index = 0;
	}

	public void update(int index, float[] vertexs) {
		index *= vertexs.length;
		for (int i = 0; i < vertexs.length; i++, index++) {
			this.vertexs.put(index , vertexs[i]);
		}
	}

	public void update(int index, float[] vertexs, float[] texcoords) {
		index *= texcoords.length;
		for (int i = 0; i < texcoords.length; i++, index++) {
			this.vertexs.put(index , vertexs[i]);
			this.texcoords.put(index , texcoords[i]);
		}
	}
	
	public void put(float[] vertexs, float[] texcoords) {
		this.vertexs.put(vertexs);
		this.texcoords.put(texcoords);
		for (short i = 0; i < indices.length; i++) {
			short ind = (short) (index * 4 + indices[i]);
			this.indexs.put(ind);
		}
		index++;
	}
	
	public void put(float[] vertexs, FloatBuffer texcoords) {
		this.vertexs.put(vertexs);
		this.texcoords.put(texcoords);
		for (short i = 0; i < indices.length; i++) {
			short ind = (short) (index * 4 + indices[i]);
			this.indexs.put(ind);
		}
		index++;
	}
	
	public void put(FloatBuffer vertexs, FloatBuffer texcoords) {
		this.vertexs.put(vertexs);
		this.texcoords.put(texcoords);
		for (short i = 0; i < indices.length; i++) {
			short ind = (short) (index * 4 + indices[i]);
			this.indexs.put(ind);
		}
		index++;
	}
	
	public void relase() {
		ClassUtil.clean(vertexBytes);
		ClassUtil.clean(texcoordBytes);
		ClassUtil.clean(indexBytes);
	}
	
}
